/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.cms.web.front;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.constant.Constant;
import com.thinkgem.jeesite.common.utils.HttpRequestUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.WxPayCommonUtil;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.cms.entity.Site;
import com.thinkgem.jeesite.modules.cms.utils.CmsUtils;
import com.thinkgem.jeesite.modules.ems.entity.Award;
import com.thinkgem.jeesite.modules.ems.entity.Course;
import com.thinkgem.jeesite.modules.ems.entity.Join;
import com.thinkgem.jeesite.modules.ems.entity.Order;
import com.thinkgem.jeesite.modules.ems.service.AwardService;
import com.thinkgem.jeesite.modules.ems.service.CourseService;
import com.thinkgem.jeesite.modules.ems.service.JoinService;
import com.thinkgem.jeesite.modules.ems.service.OrderService;
import com.thinkgem.jeesite.modules.sys.entity.Mdict;
import com.thinkgem.jeesite.modules.sys.service.MdictService;

import net.sf.json.JSONObject;
/**
 * 测试Controller
 * @author ThinkGem
 * @version 2014-02-28
 */
@Controller
@RequestMapping(value = "${frontPath}/weixin")
public class WeixinController extends BaseController {

	private static org.apache.log4j.Logger logger = LogManager.getLogger("WeixinController");
	
	@Autowired
	private CourseService courseService;
	
	@Autowired
	private JoinService joinService;
	
	@Autowired
	private MdictService mdictService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private AwardService awardService;
	
	private String proxyName="";
    private Long proxyId=0L;
    
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String index(Model model,HttpServletRequest request) {
		Site site = CmsUtils.getSite(Site.weixinSiteId());
		request.getSession().setAttribute("weiXinSiteId", Site.weixinSiteId());
		model.addAttribute("site", site);
		// model.addAttribute("isIndex", true);
		return "modules/cms/front/themes/"+site.getTheme()+"/frontIndex";
	}
	
	/**
	 * 微信报名页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "frontJoin", method = RequestMethod.GET)
	public String frontJoin(Model model,HttpServletRequest request) {
		Site site = CmsUtils.getSite(Site.weixinSiteId());
		request.getSession().setAttribute("weiXinSiteId", Site.weixinSiteId());
		model.addAttribute("site", site);
		return "modules/cms/front/themes/"+site.getTheme()+"/frontJoin";
	}
	
	/**
	 * 报名简章页面
	 */
	@RequestMapping(value = "rule")
	public String rule(String sign,Model model) {
		Site site = CmsUtils.getSite(Site.weixinSiteId());
		model.addAttribute("site", site);
		
		// 根据课程标识，查询课程信息
		Course course = this.courseService.get(sign);
		model.addAttribute("course", course);
		return "modules/cms/front/themes/"+site.getTheme()+"/frontJoinRule";
	}
	
	
	/**
	 * 报名信息填写页面
	 */
	@RequestMapping(value = "joinForm")
	public String joinForm(String sign,Model model,HttpServletRequest req,HttpServletResponse rsp) {
		Site site = CmsUtils.getSite(Site.weixinSiteId());
		model.addAttribute("site", site);
		
		Course course = this.courseService.get(sign);
		if(null ==course)
		{
			return "modules/cms/front/themes/"+site.getTheme()+"/frontIndex";
		}
		
		// 参赛大类
		List<Mdict> bigCategories = null;
		Mdict mdict = new Mdict();
		mdict.setType(Constant.Mdict.MDICT_COURSE_TYPE_PREFIX + sign);
		bigCategories = this.mdictService.findList(mdict);
		
		model.addAttribute("course", course);
		model.addAttribute("bigCategories", bigCategories);
		
		// 生成token避免重复提交
		String token = IdGen.uuid();
		model.addAttribute("token", token);
		req.getSession().setAttribute("token", token);
		return "modules/cms/front/themes/"+site.getTheme()+"/frontJoinForm";
	}
	
	
	/**
	 * 报名信息查询页面
	 */
	@RequestMapping(value = "joinSearch")
	public String joinSearch(String sign,Model model,HttpServletRequest req,HttpServletResponse rsp) {
		Site site = CmsUtils.getSite(Site.weixinSiteId());
		model.addAttribute("site", site);
		model.addAttribute("isIndex", true);
		
		Course course = this.courseService.get(sign);
		
		if(null ==course)
		{
			return "modules/cms/front/themes/"+site.getTheme()+"/frontIndex";
		}
		model.addAttribute("course", course);
		return "modules/cms/front/themes/"+site.getTheme()+"/frontJoinSearch";
	}
	
	/**
	 * 报名信息查询结果页面
	 */
	@RequestMapping(value = "joinResult")
	public String joinResult(String sign,Join join,Model model,HttpServletRequest req,HttpServletResponse rsp) {
		Site site = CmsUtils.getSite(Site.weixinSiteId());
		model.addAttribute("site", site);
		model.addAttribute("isIndex", true);
		
		Course course = this.courseService.get(sign);
		join.setCourse(course);
		if(null ==course)
		{
			return "modules/cms/front/themes/"+site.getTheme()+"/frontIndex";
		}
		model.addAttribute("course", course);
		
		/*List<Join> joins = this.joinService.findListForSearch(join);
		// 查询参赛小类（因小类无法通过sql查询，只能后台处理）
		if(null == joins || joins.size() < 1)
		{
			model.addAttribute("noData", "yes");
			return "modules/cms/front/themes/"+site.getTheme()+"/frontJoinResult";
		}*/
		
		Award award = new Award();
		award.setJoiner(join.getJoiner());
		List<Award> awards = this.awardService.findList(award);
		
		// 修改为通过sql查询 zhanganda 2017-12-08
		/*String ptype = Constant.Mdict.MDICT_COURSE_TYPE_PREFIX + sign;
		Mdict mdict = new Mdict();
		mdict.setPtype(ptype);
		List<Mdict> mdicts = this.mdictService.findList(mdict);
		for(Join j:joins)
		{
			j.setSmallCategoryName(mdictService.mdictName(mdicts, j.getSmallCategory()));
		}*/
		
		// model.addAttribute("joins", joins);
		
		model.addAttribute("awards", awards);
		if(null == awards || awards.size() < 1)
		{
			model.addAttribute("noData", "yes");
		}
		
		return "modules/cms/front/themes/"+site.getTheme()+"/frontJoinResult";
	}
	
	
	/**
	 * 报名信息保存
	 */
	@RequestMapping(value = "saveJoin")
	public String save(Join join, Model model, String token,HttpServletRequest req,RedirectAttributes redirectAttributes) {
    	Site site = CmsUtils.getSite(Site.weixinSiteId());
    	model.addAttribute("site", site);
    	String tokenSession = null == req.getSession().getAttribute("token")?null:String.valueOf(req.getSession().getAttribute("token"));
    	if(null != token && token.equals(tokenSession)){
    		
			// join.setIsNewRecord(true);
    		Order order = this.orderService.get(join.getOrder().getId());
    		join.setOrder(order);
    		join.setCreateDate(new Date());
			try{
				join.setCourse(this.courseService.get(join.getCourse().getId()));
				this.courseService.sumNumAndMoney(join.getJoinType(), join.getCourse().getOneMoney(), join.getCourse().getMultiMoney(), join.getJoiner(),join.getOrder());
				
				// 获取大类名称，用于前台展示
	    		String bigCatName = this.mdictService.getBigCatLabelByValue(Constant.Mdict.MDICT_COURSE_TYPE_PREFIX + join.getCourse().getSign(), join.getBigCategory());
	    		join.setBigCategoryName(bigCatName);
	    		String smallCatName = this.mdictService.getSmallCatByValue(Constant.Mdict.MDICT_COURSE_TYPE_PREFIX + join.getCourse().getSign(), join.getBigCategory(), join.getSmallCategory());
	    		join.setSmallCategoryName(smallCatName);
				
				model.addAttribute("join", join);
				
				// 此处不再将报名人分开单独处理，2017-12-04 zad
				// 将多个选手名称及对应id转换为list，用用后台批量插入
				// joinService.parseJionList(join);
				
				// 不再将报名人分开进行批量保存, 2017-12-04 zad
				// int rows = joinService.saveBatch(join);
				joinService.save(join);
				
				/*System.out.println("报名人数：" + order.getNum()+",插入报名信息条数：" + rows);
				if(rows < 1)
				{
					throw new Exception("插入报名信息条数为0");
				}*/
				
				
				
			}catch(Exception e)
			{
				e.printStackTrace();
				model.addAttribute("msg","报名失败，原因：" + e.getMessage());
				return "redirect:"+Global.getFrontPath()+"/"+site.getTheme()+"/joinForm?sign="+join.getCourse().getSign();
				
			}
			
			req.getSession().removeAttribute("token");
			
			// 获取支付方式
			String payType = Global.getPayType();
			model.addAttribute("payType", payType);
			
			//addMessage(redirectAttributes, "保存报名信息成功");
			// return "redirect:"+Global.getAdminPath()+"/ems/join/?repage";
			// System.out.println("modules/cms/front/themes/"+site.getTheme()+"/frontJoinPay");
			return "modules/cms/front/themes/"+site.getTheme()+"/frontJoinPay";
		}
    	return "modules/cms/front/themes/"+site.getTheme()+"/frontIndex";
    }
	
	
	//获取微信授权，通过jsp页面跳转到微信，得到微信的code
		@SuppressWarnings("deprecation")
		@RequestMapping(value = "/getCode")
		public ModelAndView getCode(HttpServletRequest request, HttpServletResponse response) throws Exception {
			ModelAndView mv = new ModelAndView();
			Site site = CmsUtils.getSite(Site.weixinSiteId());
			//通过卡号获取代理商id
			//Card card=cardService.selectByIccId(request.getParameter("iccid"));
			/*String appid;
			if("浩博数码".equals(card.getProxyName())){
				appid = WxPayCommonUtil.APPID_P;
				this.proxyName="浩博数码";
				this.proxyId=card.getProxyId();
			}else{
				appid = WxPayCommonUtil.APPID;
				this.proxyName="";
			}*/
			String appid = WxPayCommonUtil.APPID;
			String redirect_uri = URLEncoder.encode("http://www.sdsxdw.com/weixin/getInfo");
			String response_type = "code";
			String scope = "snsapi_base";
			
			
			// mode by zad 2017-11-20 url不再直接传递，而修改为后台组装
			// String state = request.getParameter("url");// 把传递的url赋值给自定义参数
			
			String orderNo = request.getParameter("ono");// 把传递的url赋值给自定义参数
			Order order = this.orderService.get(orderNo);
			if(null == order)
			{
				System.out.println("-------微信支付时，根据订单号获取订单信息为空");
				logger.error("-------微信支付时，根据订单号获取订单信息为空");
				return null;
			}
			
			String domainName = Global.getConfig("domainName");
			if(StringUtils.isBlank(domainName))
			{
				domainName = "http://www.sdsxdw.com";
			}
			
			// 生产
			String state = domainName + "/weixin/pay?oid=" + orderNo + "!p=" + order.getMoney();
			
			// 测试
			// String state = domainName + "/weixin/pay?oid=" + orderNo + "!p=0.01";
			
			
			
			String wx_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri="
					+ redirect_uri + "&response_type=" + response_type + "&scope=" + scope + "&state=" + state
					+ "#wechat_redirect";
			mv.addObject("wx_url", wx_url);
			mv.addObject("status", "1.1");
			// mv.setViewName("web/card1/wx_code");
			mv.setViewName("modules/cms/front/themes/"+site.getTheme()+"/wx_code");
			return mv;
			//最终获得到微信的code以后，会跳转到一个中间页，中间页用来接收code和state
		}
	
		@RequestMapping(value="/getInfo")
		public ModelAndView getInfo(HttpServletRequest request, HttpServletResponse response) throws IOException{
			ModelAndView mv = new ModelAndView();
			
			Site site = CmsUtils.getSite(Site.weixinSiteId());
			
			String code = request.getParameter("code");
			String state = request.getParameter("state");
			/*String appid;
			String secret;
			if("浩博数码".equals(this.proxyName)){
				appid = WxPayCommonUtil.APPID_P;
				secret = WxPayCommonUtil.APPSecret_P;
			}else{
				appid = WxPayCommonUtil.APPID;
				secret = WxPayCommonUtil.APPSecret;
			}*/
			String appid= WxPayCommonUtil.APPID;
			String secret= WxPayCommonUtil.APPSecret;
			String grant_type = "authorization_code";
			String wx_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret
					+ "&code=" + code + "&grant_type=" + grant_type + "";
			
			String data = HttpRequestUtils.sendGet(wx_url, "");
			System.out.println("----获取openId微信接口返回报文:"+data);
			logger.info("----获取openId微信接口返回报文:"+data);
			if(data.indexOf("access_token")<0){
				mv.addObject("msg", "您的操作导致微信验证失效，请重新打开");
				mv.setViewName("modules/cms/front/themes/"+site.getTheme()+"/my_warning");
				return mv;
			}
			JSONObject jsonData = JSONObject.fromObject(data);
			String access_token = jsonData.getString("access_token");
			String openid = jsonData.getString("openid");
			state +="!opid="+openid;
			mv.addObject("openid", openid);
			mv.addObject("url", state);
			mv.addObject("status", "1.1");
			mv.setViewName("modules/cms/front/themes/"+site.getTheme()+"/wx_convert");
			return mv;
		}
		
		// 微信统一下单，获取prepay_id
		public Map<String, String> weixinPrePay(String sn, String openid, BigDecimal totalAmount, String description,
				HttpServletRequest request) {
			// Setting setting = SettingUtils.get();
			SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
			/*if("浩博数码".equals(this.proxyName)){
				parameterMap.put("appid", WxPayCommonUtil.APPID_P);
				parameterMap.put("mch_id", WxPayCommonUtil.MCH_ID_P);
			}else{
				parameterMap.put("appid", WxPayCommonUtil.APPID);
				parameterMap.put("mch_id", WxPayCommonUtil.MCH_ID);
			}*/
			parameterMap.put("appid", WxPayCommonUtil.APPID);
			parameterMap.put("mch_id", WxPayCommonUtil.MCH_ID);
			parameterMap.put("nonce_str", WxPayCommonUtil.getRandomString(32));
			parameterMap.put("body", description);
			parameterMap.put("out_trade_no", sn);
			parameterMap.put("fee_type", "CNY");
			BigDecimal total = totalAmount.multiply(new BigDecimal(100));
			java.text.DecimalFormat df = new java.text.DecimalFormat("0");
			parameterMap.put("total_fee", df.format(total));
			parameterMap.put("spbill_create_ip", request.getRemoteAddr());
			parameterMap.put("notify_url", "http://www.sdsxdw.com/weixin/pay_ok.jsp");
			parameterMap.put("trade_type", "JSAPI");
			parameterMap.put("openid", openid);
			String sign = WxPayCommonUtil.createSign("UTF-8", parameterMap,this.proxyName);
			parameterMap.put("sign", sign);
			String requestXML = WxPayCommonUtil.getRequestXml(parameterMap);
			logger.info("--->>>end<<<---");
			logger.info(requestXML);
			String result = WxPayCommonUtil.httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",
					requestXML);
			logger.info(result);
			Map<String, String> map = null;
			try {
				map = WxPayCommonUtil.doXMLParse(result);
			} catch (JDOMException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return map;
		}
		
		@RequestMapping(value="/pay")
		public ModelAndView getPrePayId(HttpServletRequest request, HttpServletResponse response) {
			
			Site site = CmsUtils.getSite(Site.weixinSiteId());
			
			//ResultJson rs = new ResultJson();
			ModelAndView mv = new ModelAndView();
			Map<String, String> map = new HashMap<String, String>();
			String order_id = request.getParameter("oid");
			String open_id = request.getParameter("opid");
			float price = StringUtils.toFloat(request.getParameter("p"));
			
			
			// String title = order_id;//涉及到编码问题，暂用order_id代替title；//URLDecoder.decode(request.getParameter("t"));
			String title = "山东省少先队服务中心-报名";
			
			logger.info(title);
			map = weixinPrePay(order_id,open_id, BigDecimal.valueOf(price), title, request);
			//rs.setResult(map);
			//rs.setSuccess(true);
			//System.out.println(map.get("prepay_id"));
			String package_str = "prepay_id="+map.get("prepay_id");
			SortedMap<String, Object> mapParam = new TreeMap<String, Object>();
			String timeStamp = (System.currentTimeMillis() / 1000)+"";
			String nonceStr = WxPayCommonUtil.getRandomString(16);
			/*if("浩博数码".equals(this.proxyName)){
				mapParam.put("appId", WxPayCommonUtil.APPID_P);
			}else{
				mapParam.put("appId", WxPayCommonUtil.APPID);
			}*/
			mapParam.put("appId", WxPayCommonUtil.APPID);
			mapParam.put("timeStamp", timeStamp);
			mapParam.put("nonceStr", nonceStr);
			mapParam.put("package", package_str);
			mapParam.put("signType", "MD5");
			String paySign = WxPayCommonUtil.createSign("UTF-8", mapParam,this.proxyName);
			mapParam.put("paySign", paySign);
			
			mv.addObject("appId", mapParam.get("appId"));
			mv.addObject("timeStamp", mapParam.get("timeStamp"));
			mv.addObject("nonceStr", mapParam.get("nonceStr"));
			mv.addObject("package_s", mapParam.get("package"));
			mv.addObject("signType", mapParam.get("signType"));
			mv.addObject("paySign", mapParam.get("paySign"));
			mv.addObject("order_code", order_id);
			mv.setViewName("modules/cms/front/themes/"+site.getTheme()+"/wx_pay");
			return mv;
		}
		
		
		/*
		 * 支付成功
		 */
		@RequestMapping(value="/pay_ok")
		public ModelAndView pay_ok(HttpServletRequest request, HttpServletResponse response) throws Exception {
			
			Site site = CmsUtils.getSite(Site.weixinSiteId());
			
			ModelAndView mv = new ModelAndView();
			Map<String,String> resultMap =new HashMap<String,String>();
			//取得订单号
			String orderNo = request.getParameter("orderNo");
			//根据订单号获取订单详情
			Order order=orderService.get(orderNo);
			
			if(order==null){
				mv.addObject("remark", "支付失败！原因：没有找到订单(" + orderNo + ")，请联系管理员");
				mv.setViewName("modules/cms/front/themes/"+site.getTheme()+"/pay_fail");
				return mv;
			}
			
			//订单状态不是成功的状态时，更新为成功
			if(!Constant.Order.EMS_ORDER_STATUS_SUCCESS.equals(order.getStatus())){
				
				Order uptOrder = new Order();
				uptOrder.setStatus(Constant.Order.EMS_ORDER_STATUS_SUCCESS);
				uptOrder.setSuccessTime(new Date());
				uptOrder.setIsNewRecord(false);
				uptOrder.setId(order.getId());
				uptOrder.setRemarks("支付成功，订单完成");
				
				// 成功页面支付结果
				resultMap.put("description", "支付成功，订单完成。");
				orderService.save(uptOrder);
				
				/*Course course = this.courseService.get(order.getCourseId());
				mv.addObject("course", course);*/
				
			}else{
				resultMap.put("status", "1");
				resultMap.put("description", "该订单已经支付过！");
				resultMap.put("MsgId", orderNo);
			}
			
			mv.addObject("orderNo", orderNo);
			mv.addObject("resultMap", resultMap);
			// mv.setViewName("web/card1/pay_ok");
			mv.setViewName("modules/cms/front/themes/"+site.getTheme()+"/pay_ok");
			
			return mv;
		}
		
		
		/*
		 * 支付取消
		 */
		@RequestMapping(value="/pay_cancel")
		public ModelAndView pay_cancel(HttpServletRequest request, HttpServletResponse response) throws Exception {
			
			Site site = CmsUtils.getSite(Site.weixinSiteId());
			
			ModelAndView mv = new ModelAndView();
			//取得订单号
			String orderNo = request.getParameter("orderNo");
			//根据订单号获取订单详情
			Order order=orderService.get(orderNo);
			logger.info("===============orderNo"+orderNo);
			logger.info("===============order"+order);
			//支付取消，订单作废
			if(order!=null && "0".equals(order.getStatus())){
				Order uptOrder = new Order();
				uptOrder.setStatus(Constant.Order.EMS_ORDER_STATUS_INVALID);
				uptOrder.setSuccessTime(new Date());
				uptOrder.setIsNewRecord(false);
				uptOrder.setId(order.getId());
				uptOrder.setRemarks("支付取消，订单失效");
				orderService.save(uptOrder);
			}
			
			mv.setViewName("modules/cms/front/themes/"+site.getTheme()+"/pay_cancel");
			return mv;
		}
		
		/*
		 * 支付失败
		 */
		@RequestMapping(value="/pay_fail")
		public ModelAndView pay_fail(HttpServletRequest request, HttpServletResponse response,Model model) throws Exception {
			
			Site site = CmsUtils.getSite(Site.weixinSiteId());
			
			ModelAndView mv = new ModelAndView();
			//取得订单号
			String orderNo = request.getParameter("orderNo");
			//根据订单号获取订单详情
			Order order=orderService.get(orderNo);
			String remark = "支付失败，请联系管理员";
			//支付失败
			if(order!=null && Constant.Order.EMS_ORDER_STATUS_TOPAY.equals(order.getStatus())){
				Order uptOrder = new Order();
				uptOrder.setStatus(Constant.Order.EMS_ORDER_STATUS_FAIL);
				uptOrder.setSuccessTime(new Date());
				uptOrder.setIsNewRecord(false);
				uptOrder.setId(order.getId());
				uptOrder.setRemarks("支付失败，订单完成");
				orderService.save(uptOrder);
			}
			if(order!=null && Constant.Order.EMS_ORDER_STATUS_SUCCESS.equals(order.getStatus())){
				remark = "支付失败，原因：该订单已支付";
			}
			model.addAttribute("remark", remark);
			mv.setViewName("modules/cms/front/themes/"+site.getTheme()+"/pay_fail");
			return mv;
		}
		
		
		
		
		
		
	/**
	 * 
	 * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。 
	 * @param timestamp 时间戳
	 * @param nonce 随机数 
	 * @param echostr 随机数 
	 * @return
	 */
	/*@RequestMapping(value = "", method = RequestMethod.GET)
	@ResponseBody
	public String get(String signature, String timestamp, String nonce, String echostr, HttpServletRequest request) {
		
		System.out.println("=============================================== get start");
		for (Object o : request.getParameterMap().keySet()){
			System.out.println(o + " = " + request.getParameter((String)o));
		}
		System.out.println("=============================================== get end");
		
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败  
        if (WiexinSignUtil.checkSignature(signature, timestamp, nonce)) {  
        	return echostr;
        }

		return "";
	}

	@RequestMapping(value = "", method = RequestMethod.POST)
	@ResponseBody
	public String post(String signature, String timestamp, String nonce, String echostr, HttpServletRequest request) {
		System.out.println("=============================================== post start");
		for (Object o : request.getParameterMap().keySet()){
			System.out.println(o + " = " + request.getParameter((String)o));
		}
		System.out.println("=============================================== post end");
		StringBuilder result = new StringBuilder();
		result.append("<xml>" +
				"<ToUserName><![CDATA[toUser]]></ToUserName>" +
				"<FromUserName><![CDATA[fromUser]]></FromUserName>" +
				"<CreateTime>12345678</CreateTime>" +
				"<MsgType><![CDATA[text]]></MsgType>" +
				"<Content><![CDATA[你好]]></Content>" +
				"</xml>");
		return result.toString();
	}*/
	
		/*
		 * add by zad 2018-03-13 微信扫码支付到个人微信账号
		 */
		@RequestMapping(value = "toQRcodePay")
		public String toQRcodePay(String ono, Model model,HttpServletRequest req) throws Exception {
	    	Site site = CmsUtils.getSite(Site.weixinSiteId());
			
	    	model.addAttribute("site", site);
	    	
			Order order = this.orderService.get(ono);
			
			if(null == order)
			{
				return "modules/cms/front/themes/"+site.getTheme()+"/frontIndex";
			}
			
			Course course = this.courseService.get(order.getCourseId());
			model.addAttribute("order", order);
			model.addAttribute("course", course);
			
			return "modules/cms/front/themes/"+site.getTheme()+"/frontPersonalPay";
			
	    }
		
		/*
		 * add by zad 2018-03-13
	     * 微信支付到个人二维码图片下载
	     */
	    @RequestMapping("payPersonalQRcode")
	    public void payPersonalQRcode(HttpServletRequest request, HttpServletResponse response) throws IOException{
	    	 String templatePath = request.getSession().getServletContext().getRealPath("/upload");
	    	 String path = templatePath+"/" + Global.getConfig("weixinPersonalPayQRcode"); 
	    	File file = new File(path);// path是根据日志路径和文件名拼接出来的
	    	if(file.exists()){
	    		// String filename = file.getName();// 获取日志文件名称
	            InputStream fis = new BufferedInputStream(new FileInputStream(path));
	            byte[] buffer = new byte[fis.available()];
	            fis.read(buffer);
	            fis.close();
	            response.reset();
	            // 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
	            /*response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
	            response.addHeader("Content-Length", "" + file.length());*/
	            OutputStream os = new BufferedOutputStream(response.getOutputStream());
	            response.setContentType("multipart/form-data");
	            os.write(buffer);// 输出文件
	            os.flush();
	            os.close();
	    	}else{
	    		System.out.println("没有找到支付二维码文件");
	    	}
	    }
}
